package guowei.guliorder.order.web;

import guowei.guliorder.order.service.OrderService;
import guowei.guliorder.order.vo.OrderConfirmVo;
import guowei.guliorder.order.vo.OrderSubmitVo;
import guowei.guliorder.order.vo.SubmitOrderRespnseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class CartToTradeController {

    @Autowired
    OrderService orderService;

    /**
     * 购物车点击去结算跳转
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.getAllOrderInfo();
        System.out.println(orderConfirmVo);
        model.addAttribute("order",orderConfirmVo);
        return "settle";
    }

    /**
     * 跳转请求接收到，先验证token 若正确返回则携带订单信息返回支付页
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String confirmOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){

        SubmitOrderRespnseVo submitOrderRespnseVo = null;
        try {
            submitOrderRespnseVo = orderService.submitRespons(vo);
            if (submitOrderRespnseVo.getCode() == 0){
                model.addAttribute("response",submitOrderRespnseVo);
                return "cash";
            }else {
                String msg = "";
                switch (submitOrderRespnseVo.getCode()){
                    case 1: msg="令牌验证失败，非法获取订单请求";break;
                    case 2: msg="验价失败,商品价格信息已改变";break;
                    case 3: msg="锁定库存商品失败，商品库存不足";break;
                    case 4: msg="算数错误";break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.ganjiuwanle.com/toTrade";
            }
        } catch (Exception e) {
            String msg = "锁定库存商品失败，商品库存不足";
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.ganjiuwanle.com/toTrade";
        }
//  若提交订单请求正确返回，则跳转支付选择页    否则重定向回结算页
//        if (submitOrderRespnseVo.getCode() == 0){
//            model.addAttribute("response",submitOrderRespnseVo);
//            return "cash";
//        }else {
//            String msg = "";
//            switch (submitOrderRespnseVo.getCode()){
//                case 1: msg="令牌验证失败，非法获取订单请求";break;
//                case 2: msg="验价失败,商品价格信息已改变";break;
//                case 3: msg="锁定库存商品失败，商品库存不足";break;
//                case 4: msg="算数错误";break;
//            }
//            redirectAttributes.addFlashAttribute("msg",msg);
//            return "redirect:http://order.ganjiuwanle.com/toTrade";
//        }
    }
}